<?php

namespace App\Console\Commands;

use App\Models\AppMiniPlate;
use App\Models\AppTypeModel;
use App\Models\Order;
use App\Models\OrderLease;
use App\Models\OtherWithholdLog;
use App\Models\ShopTrans;
use App\Services\AlipayService;
use App\Services\CommonService;
use App\Services\EsignService;
use App\Services\GoodsService;
use App\Services\OrderService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class FinanceCheckOrderSettleCommand extends BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'financeCheckOrderSettle';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '平台商家订单结算';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    protected function handleExec()
    {
        $this->financeCheckOrderSettle();
    }

    const TIME_LIMIT = 3; //单位小时
    const ORDER_NUM_LIMIT = 200; //一次操作订单数量


    /**
     * 签约未支付订单分期账单到期易付宝扣款付款
     */
    public function financeCheckOrderSettle()
    {
        try {
            $where[] = ['o.pay_type', '!=', Order::ORDER_PAY_TYPE_HUABEI];
            $where[] = ['ol.status', OrderLease::ORDER_LEASE_STATUS_PAID];
            $where[] = ['ol.settle_type', OrderLease::ORDER_LEASE_SETTLE_STATUS_NO];
            $order = OrderLease::from('sp_order_lease_2 as ol')->where($where)
                ->wherein('o.status', OrderService::getOrderStatus(OrderService::ORDER_SETTLE_CONFIRM_STATUS))
                ->where('o.seller_id','!=','1704471788')
                ->leftjoin('sp_order_2 as o', 'o.id', 'ol.order_id')
                ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
                ->select('ol.id as lease_id', 'ol.order_id', 'o.trade_no', 'o.seller_id', 'o.month_total',
                    'ol.which_period', 'o.begin_time', 'o.end_time', 'og.goods_title', 'og.lease_set'
                    , 'og.lease_time', 'ol.begin_time as lease_time', 'ol.pay_type'
                    , 'ol.pay_time', 'ol.rent', 'ol.paid_rent', 'ol.status as lease_status',
                    'ol.settle_amount', 'ol.settle_time', 'o.realname', 'o.mobile',
                    'o.prov', 'o.city', 'o.area', 'o.address', 'o.financing_type',
                    'o.status as order_status', 'ol.overdue_days', 'ol.settle_type',
                    'ol.reason', 's.shopname', 'o.sync_status')->orderBy('ol.id', 'desc')->get();
            $order = obToArray($order);

            foreach ($order as $ra) {
                $data = $this->orderSettle($ra['lease_id']);

                $data = json_decode($data, true);
                if ($data['status'] != 200) {
                    $this->infoLog('平台商家订单结算'.$ra['lease_id'], $data);
                } else {
                    $this->infoLog('平台商家订单结算'.$ra['lease_id'] . $data['msg']);
                }
            }
        } catch (\Exception $exception) {
            $this->infoLog('平台商家订单结算失败');
        }

    }

    /**
     * 账单结算--单期结算
     */
    public function orderSettle($lease_id)
    {
        if (!empty($lease_id)) {
            $order = OrderLease::from('sp_order_lease_2 as ol')->where('ol.id',$lease_id)
                ->wherein('ol.status',[OrderLease::ORDER_LEASE_STATUS_PAID,OrderLease::ORDER_LEASE_STATUS_BUYOUT])
                ->leftjoin('sp_order_2 as o','o.id','ol.order_id')
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->select('o.id as order_id','o.trade_no','o.month_total','og.is_buy_out','o.order_from','o.seller_id','ol.which_period','ol.which_period','ol.rent',
                    'o.uid','ol.alipay_trade_no','o.is_insurance_choose','o.is_insurance_choose_custom',
                    'o.rent_total','o.financing_type','ol.paid_rent',
                    'o.is_skip','o.is_skip','og.goods_id','o.amount','og.pact_type', 'og.setmeal_foregift')->first();

            $order = obToArray($order);
//            dd($order['is_preposition']);
            if(!empty($order)){
                $settle_data = ShopTrans::getSettleData($order);
                if(empty($settle_data)){
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单来源费率未设置');
                }
                if(!empty($settle_data)){
                    unset($settle_data['trans_detail']['insure_rate']);

                    $order=array_merge($order,$settle_data['trans_detail']);
                    if($order['pact_type']==1){
                        $order['rent_total']=bcadd($order['setmeal_foregift']*$order['amount'],GoodsService::getGoodsInsurance($order['is_insurance_choose'],$order['is_insurance_choose_custom']),2);
                    }else{
                        $order['rent_total'] =$order['rent_total'];
                    }

                    if ($settle_data['is_preposition'] == 1 && $order['which_period'] == 1) {
                        $service_fee = sprintf("%.4f", $order['rent_total'] * $settle_data['fee_rate'] * 0.01 + $settle_data['fixed_fee']+bcmul($order['paid_rent'] , $settle_data['post_deduction'] * 0.01,2));
                        $settle_amount = sprintf("%.4f", $order['paid_rent'] - $service_fee);
                        $remarks = '前置结算，第' . $order['which_period'] . '期结算';
                        $settle_data['trans_detail']['platform_amount'] = sprintf("%.4f", $order['rent_total'] * $settle_data['trans_detail']['platform_rate'] * 0.01);
                        $settle_data['trans_detail']['insurance_amount'] = sprintf("%.4f", $order['rent_total'] * $settle_data['trans_detail']['insurance_rate'] * 0.01);
                        $settle_data['trans_detail']['insurance_amount'] = sprintf("%.4f", $order['rent_total'] * $settle_data['trans_detail']['financing_rate'] * 0.01);
                        $settle_data['trans_detail']['file_amount'] = sprintf("%.4f", $order['rent_total'] * $settle_data['trans_detail']['file_rate'] * 0.01);
                        $settle_data['trans_detail']['withhold_amount'] = sprintf("%.4f", $order['rent_total'] * $settle_data['trans_detail']['withhold_rate'] * 0.01);

                        $res = ShopTrans::addOrderTrans($order, $settle_amount, $service_fee, $order['alipay_trade_no'],
                            $remarks, $lease_id, $settle_data['fee_rate'], $settle_data['fixed_fee'],
                            $settle_data['trans_detail'], ShopTrans::ORDER_TRANS_TYPE_SETTLE);
                        if ($res) {
                            $data['settle_type'] = OrderLease::ORDER_LEASE_SETTLE_STATUS_YES;
                            $data['settle_amount'] = $settle_amount;
                            $data['settle_time'] = date('Y-m-d H:i:s');
                            $ol_res = OrderLease::where('id', $lease_id)->update($data);
                            if ($ol_res) {
                                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '结算成功1');
                            } else {
                                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '结算失败0');
                            }
                        } else {
                            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '结算失败0');
                        }
                    } else if ($settle_data['is_preposition'] == 1) {
                        $service_fee = bcmul($order['paid_rent'] , $settle_data['post_deduction'] * 0.01,2);
                        $settle_amount = sprintf("%.4f", $order['paid_rent'] - $service_fee);
                        $remarks = '已前置结算，第' . $order['which_period'] . '期结算';
                        $settle_data['trans_detail']['platform_amount'] = 0;
                        $settle_data['trans_detail']['insurance_amount'] = 0;
                        $settle_data['trans_detail']['insurance_amount'] = 0;
                        $settle_data['trans_detail']['file_amount'] = 0;
                        $settle_data['trans_detail']['withhold_amount'] = 0;

                        $res = ShopTrans::addOrderTrans($order, $settle_amount, $service_fee, $order['alipay_trade_no'], $remarks, $lease_id, $settle_data['fee_rate'], $settle_data['fixed_fee'], $settle_data['trans_detail'], ShopTrans::ORDER_TRANS_TYPE_SETTLE);
                        if ($res) {
                            $data['settle_type'] = OrderLease::ORDER_LEASE_SETTLE_STATUS_YES;
                            $data['settle_amount'] = $settle_amount;
                            $data['settle_time'] = date('Y-m-d H:i:s');
                            $ol_res = OrderLease::where('id', $lease_id)->update($data);
                            if ($ol_res) {
                                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '结算成功2');
                            } else {
                                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '结算失败1');
                            }
                        } else {
                            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '结算失败2');
                        }
                    } else {
                        $service_fee = sprintf("%.4f", $order['paid_rent'] * $settle_data['fee_rate'] * 0.01 + $settle_data['fixed_fee']);
                        $settle_amount = sprintf("%.4f", $order['paid_rent'] - $service_fee);
                        $remarks = '第' . $order['which_period'] . '期结算';
                        $settle_data['trans_detail']['platform_amount'] = sprintf("%.4f", $order['paid_rent'] * $settle_data['trans_detail']['platform_rate'] * 0.01);
                        $settle_data['trans_detail']['insurance_amount'] = sprintf("%.4f", $order['paid_rent'] * $settle_data['trans_detail']['insurance_rate'] * 0.01);
                        $settle_data['trans_detail']['insurance_amount'] = sprintf("%.4f", $order['paid_rent'] * $settle_data['trans_detail']['financing_rate'] * 0.01);
                        $settle_data['trans_detail']['file_amount'] = sprintf("%.4f", $order['paid_rent'] * $settle_data['trans_detail']['file_rate'] * 0.01);
                        $settle_data['trans_detail']['withhold_amount'] = sprintf("%.4f", $order['paid_rent'] * $settle_data['trans_detail']['withhold_rate'] * 0.01);

                        $res = ShopTrans::addOrderTrans($order, $settle_amount, $service_fee, $order['alipay_trade_no'], $remarks, $lease_id, $settle_data['fee_rate'], $settle_data['fixed_fee'], $settle_data['trans_detail'], ShopTrans::ORDER_TRANS_TYPE_SETTLE);
                        if ($res) {
                            $data['settle_type'] = OrderLease::ORDER_LEASE_SETTLE_STATUS_YES;
                            $data['settle_amount'] = $settle_amount;
                            $data['settle_time'] = date('Y-m-d H:i:s');
                            $ol_res = OrderLease::where('id', $lease_id)->update($data);

                            if ($ol_res) {
                                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '结算成功3');
                            } else {
                                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '结算失败3');
                            }
                        } else {
                            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '结算失败4');
                        }
                    }

                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '结算失败5！');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要结算的账单');
        }
    }
}
